<template>
  <div class="zerenshu-container">
    <div class="page-header">
      <div class="header-actions">
        <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
        <span>
          <el-button type="primary" @click="goToList" icon="el-icon-menu"
            >列表</el-button
          >
          <el-button type="info" icon="el-icon-printer" @click="printForm"
            >打印</el-button
          >
        </span>
      </div>
      <h1>岗位职责目标责任书</h1>
    </div>

    <el-form ref="form" :model="formData" :rules="rules" class="main-form">
      <div class="form-section">
        <table class="info-table">
          <tbody>
            <tr>
              <td class="label-cell">姓名：</td>
              <td>
                <el-form-item prop="name"
                  ><el-input
                    v-model="formData.name"
                    :disabled="isView"
                  ></el-input
                ></el-form-item>
              </td>
              <td class="label-cell">部门：</td>
              <td>
                <el-form-item prop="department"
                  ><el-input
                    v-model="formData.department"
                    :disabled="isView"
                  ></el-input
                ></el-form-item>
              </td>
              <td class="label-cell">入职日期：</td>
              <td>
                <el-form-item prop="entryDate">
                  <el-date-picker
                    v-model="formData.entryDate"
                    type="date"
                    placeholder="选择日期"
                    :disabled="isView"
                    :picker-options="pickerOptions"
                    value-format="yyyy-MM-dd"
                    @change="(val) => handleDateChange('entryDate', val)"
                  ></el-date-picker>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="label-cell">岗位：</td>
              <td>
                <el-form-item prop="position"
                  ><el-input
                    v-model="formData.position"
                    :disabled="isView"
                  ></el-input
                ></el-form-item>
              </td>
              <td class="label-cell">身份证：</td>
              <td>
                <el-form-item prop="idCard"
                  ><el-input
                    v-model="formData.idCard"
                    :disabled="isView"
                  ></el-input
                ></el-form-item>
              </td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="form-section agreement-text">
        经与
        <el-form-item prop="companyName" class="inline-form-item">
          <el-input
            v-model="formData.companyName"
            :disabled="isView"
          ></el-input>
        </el-form-item>
        公司协商一致，本人自愿签订本岗位职责，岗位目标责任书，以便双方遵照执行。
      </div>

      <div class="form-section">
        <table class="content-table">
          <thead>
            <tr>
              <th colspan="2">一、岗位职责：</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(responsibility, index) in formData.responsibilities"
              :key="index"
            >
              <td class="number-cell">{{ index + 1 }}、</td>
              <td>
                <el-input
                  v-model="formData.responsibilities[index]"
                  :disabled="isView"
                  type="textarea"
                  :rows="2"
                ></el-input>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="form-section">
        <table class="content-table">
          <thead>
            <tr>
              <th colspan="2">二、岗位目标：</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(goal, index) in formData.goals" :key="index">
              <td class="number-cell">{{ index + 1 }}、</td>
              <td>
                <el-input
                  v-model="formData.goals[index]"
                  :disabled="isView"
                  type="textarea"
                  :rows="2"
                ></el-input>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="form-section">
        <table class="content-table">
          <thead>
            <tr>
              <th colspan="2">三、其它说明：</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td class="number-cell">1、</td>
              <td>本责任书作为《劳动合同》的附件，与劳动合同具有同等效力。</td>
            </tr>
            <tr>
              <td class="number-cell">2、</td>
              <td>本责任书自员工签字之日起生效。</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="form-section signature-section">
        <p class="disclaimer-text">
          签字人确认对以上描述的岗位职责，制定的岗位目标及其它说明项清楚知悉，同意按照责任书履行义务，如不能履行以上岗位职责，达到确定的岗位目标，本人同意用人单位有权解除劳动合同并无需支付任何经济补偿金或赔偿金。
        </p>
        <div class="signature-row">
          <span class="signature-label">本人签名（手印）：</span>
          <el-form-item prop="signature" class="signature-input">
            <el-input
              v-model="formData.signature"
              :disabled="isView"
            ></el-input>
          </el-form-item>
          <span class="signature-label">日期：</span>
          <el-form-item prop="signDate" class="date-input">
            <el-date-picker
              v-model="formData.signDate"
              type="date"
              :disabled="isView"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              @change="(val) => handleDateChange('signDate', val)"
            ></el-date-picker>
          </el-form-item>
        </div>
      </div>

      <div class="form-actions" v-if="!isView">
        <el-button type="primary" icon="el-icon-check" @click="handleSubmit"
          >提交</el-button
        >
        <el-button icon="el-icon-refresh-left" @click="handleReset"
          >重置</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  createZerenshu,
  updateZerenshu,
  getZerenshuDetail,
} from "@/api/zerenshu";
import { Message } from "element-ui";

export default {
  data() {
    return {
      formData: {
        name: "",
        department: "",
        entryDate: "",
        position: "",
        idCard: "",
        companyName: "",
        responsibilities: new Array(8).fill(""),
        goals: new Array(6).fill(""),
        signature: "",
        signDate: "",
      },
      isEdit: false,
      isView: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一个月前",
            onClick(picker) {
              const date = new Date();
              date.setMonth(date.getMonth() - 1);
              picker.$emit("pick", date);
            },
          },
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一个月后",
            onClick(picker) {
              const date = new Date();
              date.setMonth(date.getMonth() + 1);
              picker.$emit("pick", date);
            },
          },
        ],
        disabledDate: null,
      },
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        department: [
          { required: true, message: "请输入部门", trigger: "blur" },
        ],
        entryDate: [
          { required: true, message: "请选择入职日期", trigger: "change" },
        ],
        position: [{ required: true, message: "请输入岗位", trigger: "blur" }],
        idCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证号",
            trigger: "blur",
          },
        ],
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
        ],
        signature: [{ required: true, message: "请输入签名", trigger: "blur" }],
        signDate: [
          { required: true, message: "请选择签署日期", trigger: "change" },
        ],
      },
    };
  },
  created() {
    const id = this.$route.query.id;
    const type = this.$route.query.type;

    if (id) {
      this.isEdit = type === "edit";
      this.isView = type === "view";
      this.loadData(id);
    }
  },
  methods: {
    printForm() {
      window.print();
    },
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    handleDateChange(field, value) {
      this.formData[field] = value;
    },

    async loadData(id) {
      try {
        const res = await getZerenshuDetail(id);
        console.log("加载数据：", res);

        if (res.data) {
          if (res.data.entryDate) {
            res.data.entryDate = this.formatDate(res.data.entryDate);
          }
          if (res.data.signDate) {
            res.data.signDate = this.formatDate(res.data.signDate);
          }

          try {
            res.data.responsibilities = res.data.responsibilities
              ? JSON.parse(res.data.responsibilities)
              : new Array(8).fill("");
            res.data.goals = res.data.goals
              ? JSON.parse(res.data.goals)
              : new Array(6).fill("");
          } catch (e) {
            res.data.responsibilities = new Array(8).fill("");
            res.data.goals = new Array(6).fill("");
          }

          while (res.data.responsibilities.length < 8) {
            res.data.responsibilities.push("");
          }
          while (res.data.goals.length < 6) {
            res.data.goals.push("");
          }

          this.formData = res.data;
        } else {
          this.initFormData();
        }
      } catch (error) {
        console.error("加载数据失败:", error);
        this.$message.error("加载数据失败");
        this.initFormData();
      }
    },
    initFormData() {
      this.formData = {
        name: "",
        department: "",
        entryDate: "",
        position: "",
        idCard: "",
        companyName: "",
        responsibilities: new Array(8).fill(""),
        goals: new Array(6).fill(""),
        signature: "",
        signDate: "",
      };
    },
    async handleSubmit() {
      try {
        await this.$refs.form.validate();

        const submitData = {
          ...this.formData,
          entryDate: this.formData.entryDate
            ? this.formatDate(this.formData.entryDate)
            : null,
          signDate: this.formData.signDate
            ? this.formatDate(this.formData.signDate)
            : null,
          responsibilities: JSON.stringify(
            this.formData.responsibilities.filter((item) => item.trim() !== "")
          ),
          goals: JSON.stringify(
            this.formData.goals.filter((item) => item.trim() !== "")
          ),
        };

        if (this.isEdit) {
          await updateZerenshu(this.$route.query.id, submitData);
          this.$message.success("更新成功");
        } else {
          await createZerenshu(submitData);
          this.$message.success("保存成功");
        }
        this.$router.push("/main/biao/zerenshuList");
      } catch (error) {
        if (error.message) {
          this.$message.error(error.message);
        } else {
          this.$message.error("表单验证失败，请检查必填项");
        }
      }
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.formData.responsibilities = new Array(8).fill("");
      this.formData.goals = new Array(6).fill("");
    },
    goBack() {
      this.$router.push("/main/biao");
    },
    goToList() {
      this.$router.push("/main/biao/zerenshuList");
    },
  },
};
</script>

<style lang="scss" scoped>
.zerenshu-container {
  padding: 16px;
  // background-color: #f5f7fa;
  min-height: 100vh;
  width: 210mm;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 16px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 12px 16px;

  .header-actions {
    display: flex;
    justify-content: space-between;
    gap: 8px;
    // margin-bottom: 12px;
  }

  h1 {
    text-align: center;
    color: #2c3e50;
    font-size: 20px;
    margin: 0;
    font-weight: 600;
  }
}

.main-form {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.form-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 16px;

  td {
    padding: 8px;
    vertical-align: middle;

    &.label-cell {
      width: 80px;
      text-align: right;
      color: #606266;
      font-weight: 500;
      white-space: nowrap;
    }
  }

  .el-form-item {
    margin-bottom: 0;
  }
}

.content-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  overflow: hidden;

  th {
    background: #409eff;
    color: white;
    padding: 10px 12px;
    font-size: 15px;
    font-weight: 600;
    text-align: left;
  }

  td {
    padding: 8px 12px;
    border: 1px solid #ebeef5;

    &.number-cell {
      width: 40px;
      text-align: center;
      background: #f5f7fa;
      color: #606266;
      font-weight: 500;
    }
  }

  :deep(.el-textarea__inner) {
    border: none;
    background: transparent;
    padding: 4px;
    min-height: 60px;

    &:hover,
    &:focus {
      background: #f5f7fa;
    }
  }
}

.agreement-text {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  padding: 0 12px;
  margin: 12px 0;

  .inline-form-item {
    display: inline-block;
    width: 180px;
    margin: 0 4px;
  }
}

.signature-section {
  .disclaimer-text {
    margin-bottom: 16px;
    line-height: 1.6;
    color: #606266;
    font-size: 14px;
  }

  .signature-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;

    .signature-label {
      color: #606266;
      font-weight: 500;
      font-size: 14px;
    }

    .signature-input {
      width: 160px;
      margin: 0;
    }

    .date-input {
      width: 160px;
      margin: 0;
    }
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;

  .el-button {
    padding: 8px 24px;
    font-size: 14px;
  }
}

:deep(.el-input__inner) {
  border-radius: 4px;
  transition: all 0.3s;
  height: 32px;
  line-height: 32px;
  padding: 0 8px;

  &:hover {
    border-color: #409eff;
  }

  &:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
  }
}

:deep(.el-form-item.is-error .el-input__inner) {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.1);
}

@media screen and (max-width: 768px) {
  .zerenshu-container {
    padding: 12px;
  }

  .page-header {
    padding: 12px;

    .header-actions {
      flex-direction: column;
    }

    h1 {
      font-size: 18px;
    }
  }

  .main-form {
    padding: 16px;
  }

  .info-table {
    td {
      display: block;
      width: 100%;
      padding: 4px 8px;

      &.label-cell {
        text-align: left;
        padding-bottom: 2px;
      }
    }
  }

  .content-table {
    td {
      padding: 8px;

      &.number-cell {
        width: 32px;
      }
    }
  }

  .signature-section {
    .signature-row {
      flex-direction: column;
      align-items: stretch;
      gap: 8px;

      .signature-input,
      .date-input {
        width: 100%;
      }
    }
  }

  .form-actions {
    flex-direction: column;
    gap: 8px;
    margin-top: 20px;
    padding-top: 12px;

    .el-button {
      width: 100%;
    }
  }
}

@media print {
  .zerenshu-container {
    padding: 0;
    background: none;
  }

  .page-header {
      box-shadow: none;
    .header-actions {
      display: none;
    }

    h1 {
      margin-bottom: 20px;
    }
  }

  .main-form {
    box-shadow: none;
    padding: 0;
  }

  .content-table {
    border: 1px solid #000;

    th,
    td {
      border: 1px solid #000;
    }
  }

  .form-actions {
    display: none;
  }
  
  textarea {
    border: 0px !important;
  }
::v-deep input.el-input__inner {
    border: none !important;
  }
  ::v-deep textarea.el-textarea__inner {
    border: none !important;
    resize: none;
  }
  ::v-deep i.el-input__icon {
    display: none !important;
  }
}
</style>